﻿namespace DimensionsHelper.ExcelAddIn.Core.Sql;

/// <summary>
/// SQL脚本生成器的样本记录类
/// </summary>
public class Record
{

    private readonly string _fieldName;
    private readonly string _value;
    private readonly HashSet<string> _samples;

    /// <summary>
    /// 创建SQL脚本生成器的样本记录
    /// </summary>
    /// <param name="fieldName">字段名</param>
    /// <param name="value">字段值</param>
    public Record(string fieldName, string value)
    {
        _fieldName = fieldName;
        _value = value;
        _samples = [];
    }


    /// <summary>
    /// 获取字段名
    /// </summary>
    public string FieldName => _fieldName;

    /// <summary>
    /// 获取字段值
    /// </summary>
    public string Value => _value;

    /// <summary>
    /// 将指定样本ID添加到记录中
    /// </summary>
    /// <param name="sampleId">样本Id</param>
    /// <returns>如果指定样本不在当前集合中，返回true</returns>
    public bool Add(string sampleId)
    {
        return _samples.Add(sampleId);
    }

    /// <summary>
    /// 将指定样本ID从记录中移除
    /// </summary>
    /// <param name="sampleId">样本ID</param>
    /// <returns>如果指定的样本ID存在并成功移除，返回true</returns>
    public bool Remove(string sampleId)
    {
        return _samples.Remove(sampleId);
    }

    /// <summary>
    /// 统计当前记录中的样本值
    /// </summary>
    /// <param name="weightingMap">样本权值表</param>
    /// <returns>样本统计数</returns>
    public double Count(Dictionary<string, double>? weightingMap)
    {
        if (weightingMap == null)
        {
            return _samples.Count;
        }

        return _samples.Select(s => weightingMap.TryGetValue(s, out var factor) ? factor : 1)
                       .Aggregate((a, b) => a + b);
    }

}
